from django.contrib import admin
from django.utils.html import format_html
from .models import Story


@admin.register(Story)
class StoryAdmin(admin.ModelAdmin):
    """故事管理后台"""
    list_display = ['title', 'author', 'category', 'status', 'review_status', 'likes', 'views', 'created_at']
    list_filter = ['status', 'review_status', 'category', 'created_at']
    search_fields = ['title', 'content', 'author__name']
    ordering = ['-created_at']
    readonly_fields = ['likes', 'views', 'created_at', 'updated_at']
    actions = ['approve_stories', 'reject_stories']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'content', 'category', 'status', 'author')
        }),
        ('审核信息', {
            'fields': ('review_status', 'review_note')
        }),
        ('统计信息', {
            'fields': ('likes', 'views', 'tags')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at', 'published_at')
        }),
    )
    
    def save_model(self, request, obj, form, change):
        """保存时处理"""
        if not change:  # 新建时自动设置作者
            obj.author = request.user
        super().save_model(request, obj, form, change)
    
    def has_delete_permission(self, request, obj=None):
        """禁止删除故事"""
        return False
    
    def approve_stories(self, request, queryset):
        """批准故事"""
        updated = queryset.update(review_status='approved')
        self.message_user(request, f'成功批准 {updated} 个故事')
    approve_stories.short_description = '批准选中的故事'
    
    def reject_stories(self, request, queryset):
        """驳回故事 - 将状态改为草稿"""
        updated = 0
        for story in queryset:
            story.review_status = 'rejected'
            story.status = 'draft'
            story.save()
            updated += 1
        self.message_user(request, f'成功驳回 {updated} 个故事，已将状态改为草稿')
    reject_stories.short_description = '驳回选中的故事（改为草稿）'
